package filter;

import domain.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CheckLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
       //先将父类向下转型
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;


        //项目中的静态资源不能拦截
        String uri = request.getRequestURI();
        //判断   /css/  这里就可以表示css文件下的任何资源了
        if(uri.contains("/css/")||uri.contains("/images/")||uri.contains("/js/")){
           chain.doFilter(request,response);
           return;
        }

        //请求登录页面的时候得放行
        String servletPath = request.getServletPath();
        if(servletPath.contains("/userLoginServlet") || servletPath.contains("/login.jsp")){
                 chain.doFilter(request,response);
                 return;
        }

        User user = (User)request.getSession().getAttribute("user");
        //判断是否能取到  如果不能取到 说明没有登录
        if(user==null){
            request.setAttribute("errorMsg","请先登录!!!");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
           //这样就跳出了不会再执行后面的放行了
            return;
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
